﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using Spring.Data;
using Spring.Data.Common;
using Spring.Data.Core;

namespace Vision.Utilities.CMS6UpdateTool
{
    public static class AdoUtility
    {
        const string DbProviderType = "System.Data.SqlClient";

        public static IDbProvider GetDbProvider(string connectionString)
        {
            var dbProvider = DbProviderFactory.GetDbProvider(DbProviderType);
            dbProvider.ConnectionString = connectionString;
            return dbProvider;
        }

        public static IAdoOperations GetAdoOperations(string connectionString)
        {
            return new AdoTemplate(GetDbProvider(connectionString));
        }

        public static string GetSqlTextFromFile(string fileFullName)
        {
            if (!string.IsNullOrEmpty(fileFullName) && File.Exists(fileFullName))
            {
                var sqlText = string.Empty;
                using (var streamReader = new StreamReader(fileFullName))
                {
                    sqlText = streamReader.ReadToEnd();
                }
                sqlText = sqlText.Replace("\r\n", " ");
                sqlText = sqlText.Replace(" GO ", " ");
                return sqlText;
            }
            return string.Empty;
        }

        public static int ExecuteNonQueryFromFile(this IAdoOperations operations, string sqlFileFullName)
        {
            var sqlText = GetSqlTextFromFile(sqlFileFullName);
            if (!string.IsNullOrEmpty(sqlText))
                return operations.ExecuteNonQuery(System.Data.CommandType.Text, sqlText);
            return 0;
        }
    }
}